import React from 'react'
import View from 'lib/View.jsx'
// import Layout from '../common/layout.jsx'
import Tab from 'lib/components/tab.jsx'
import Card from 'lib/components/card.jsx'
import ChartWidget from 'lib/components/ChartWidget.jsx'
import TogglePanel from './TogglePanel.jsx'
// import Topbar from 'lib/components/TopbarWidget.jsx'
import ActiveUserGrid from './ActiveUserGrid.jsx'
import ActiveBusyGrid from './ActiveBusyGrid.jsx'
import ActiveIdleGrid from './ActiveIdleGrid.jsx'
import MultiCheckItem from './MultiCheckItem.jsx'
import DateComparerPicker from '../common/DateComparerPicker.jsx'
import tips from '../common/indicator-tips.jsx'
import dispatcher from 'lib/dispatcher'
import cx from 'classnames'
import moment from 'moment'
import RootScope from './RootScope.es6'
import DeleableButtons from './DeleableButtons.jsx'
import _ from 'underscore'

class Card2 extends Card {
  constructor (props) {
    super(props);
    this.state = {
      showContent: true
    }
  }

  removeFilterHandler(target) {
    dispatcher.dispatch({
      $type: 'remove_filter',
      target
    })
  }

  redrawLineChart() {
    dispatcher.dispatch({
      $type: 'load_data'
    })
  }

  renderTitle() {
    return (
      <div className="widget-title">
        <div className="float-right">
          {
            <button
              className="btn-green btn-sm"
              onClick={this.redrawLineChart}>
              绘制筛选
            </button>
          }
          {
            this.props.useToggle ? (this.state.showContent ? (
              <a className="iconfont" href="javascript:;" onClick={this.slideUp.bind(this)}>&#xe611;</a>
            ) : (
              <a className="iconfont" href="javascript:;" onClick={this.slideDown.bind(this)}>&#xe610;</a>
            )) : null
          }
        </div>
        {
          <div>
            <h4>
              筛选条件：
              <DeleableButtons list={this.props.list} onClick={this.removeFilterHandler.bind(this)} />
            </h4>
          </div>
        }
      </div>
    )
  }

}

export default class RootView extends View {

  dayTypeChangeHandler (newType) {
    if(this.state.dayTypeState !== newType) {
      dispatcher.dispatch({
        $type: 'day_type_changed',
        newType: newType
      });
    }
  }

  componentDidMount() {
    super.componentDidMount();

    let versions = this.refs.versions;
    let channels = this.refs.channels;
    window.onresize = function () {
      let isChanged = false;
      let newState = {};

      if (this.lastVersionHeight !== versions.offsetHeight) {
        this.lastVersionHeight = versions.offsetHeight;
        newState.showVersionControlButton = this.lastVersionHeight > 34;
        isChanged = true;
      }

      if (this.lastChannelHeight !== channels.offsetHeight) {
        this.lastChannelHeight = channels.offsetHeight;
        newState.showChannelControlButton = this.lastChannelHeight > 34;

        isChanged = true;
      }

      if (isChanged) {
        this.setState(newState);
      }
    }.bind(this);

    setTimeout(window.onresize, 300);
  }

  componentWillUnmount() {
    window.onresize = null;

    super.componentWillUnmount();
  }

  render() {
    // debugger;
    // versions
    let versions = this.state.versions.map((item) => {
      return (<MultiCheckItem item={item} itemType="id" checkName="版本: " checkType="version" key={'active-analysis-version-' + item.id}/>);
    });
    // channels
    let channels = this.state.channels.map((item) => {
      return (<MultiCheckItem item={item} itemType="name" checkName="渠道: " checkType="channel" key={'active-analysis-channel-' + item.id}/>);
    });

    let duration = this.state.duration();
    let days = duration.asDays();

    let exportUrl = 'javascript:;';
    if (this.state.grid._originalData) {
      let dataSource = _.chain(this.state.grid._originalData)
      let first = dataSource.first().value();
      let last = dataSource.last().value();

      exportUrl = BlueWare.urlPrefix + '/app/' + BlueWare.appId + '/useranalysis/useraliveexportxls';
      exportUrl += '?timeUnit=' + this.state.dayTypeState;
      exportUrl += '&startTime=' + (last ? last.startTime : moment().valueOf());
      exportUrl += '&endTime=' + (first ? first.endTime : moment().valueOf());

      if (this.state.versionFilter) {
          exportUrl += '&appVersionId=' + this.state.versionFilter;
      }

      if (this.state.channelFilter) {
        exportUrl += '&channel=' + this.state.channelFilter;
      }
    }

    return (
      <div>
        <div className="float-position-relative">

          <div className="pure-g">
            <div className="pure-u-1">
              <div className="box">
                <Card2 title={'筛选条件'} list={this.state.filterList}>
                  <TogglePanel height={30} hidden={_.some(this.state.filterList, item => item.type === 'version')} showControlButton={this.state.showVersionControlButton}>
                    <div className="tabs-select" style={{marginBottom: 0}}>
                      <div className="pure-g">
                        <div className="pure-u-3-24 pure-u-xl-1-12">
                          <h5 style={{'float': 'left', 'margin': '3px 10px auto'}}>版本：</h5>
                        </div>
                        <div ref="versions" className="pure-u-21-24 pure-u-xl-11-12">
                          <ul>{versions}</ul>
                        </div>
                      </div>
                    </div>
                  </TogglePanel>
                  <TogglePanel height={30} hidden={_.some(this.state.filterList, item => item.type === 'channel')} showControlButton={this.state.showChannelControlButton}>
                    <div ref="channels" className="tabs-select">
                      <div className="pure-g">
                        <div className="pure-u-3-24 pure-u-xl-1-12">
                          <h5 style={{'float': 'left', 'margin': '3px 10px auto'}}>渠道：</h5>
                        </div>
                        <div className="pure-u-21-24 pure-u-xl-11-12">
                          <ul>{channels}</ul>
                        </div>
                      </div>
                    </div>
                  </TogglePanel>
                </Card2>
              </div>
            </div>
          </div>

          <div className="pure-g">
            <div className="pure-u-1">
              <div className="box">
                <Tab>
                  <Tab.Panel title="活跃用户" key="1">
                    <div className="pure-g">
                      <div className="pure-u-1">
                        <Card
                          title={
                            <span>
                              活跃用户
                              <i className="iconfont" data-tip={tips.activeanalysis_activeuser}>&#xe663;</i>
                            </span>
                          }
                          extra={
                            <div>
                            <DateComparerPicker
                              id="aliveUser"
                              spanTime={duration.valueOf()}
                              endTime={this.state.aliveUserComparer.endTime}
                              displayText={this.state.aliveUserComparer.displayText}
                              style={{
                                float:'right',
                                marginLeft:'5px',
                                marginTop:'-7px'
                              }} />
                            <div className="switch-group" style={{marginTop:'0px'}}>
                              <button onClick={this.dayTypeChangeHandler.bind(this, 'daily')}
                                 key="daily"
                                 className={cx({active: this.state.dayTypeState === 'daily'})}
                                 style={{
                                   display: days >= 1 ? 'block' : 'none'
                                 }}>
                                 日
                              </button>
                              <button onClick={this.dayTypeChangeHandler.bind(this, 'weekly')}
                                 key="weekly"
                                 className={cx({
                                   active: this.state.dayTypeState === 'weekly',
                                   disabled: days < 7
                                 })}
                                 disabled={days < 7}
                                 style={{
                                   cursor: days < 7 ? 'not-allowed' : 'pointer'
                                 }}>
                                 周
                              </button>
                              <button onClick={this.dayTypeChangeHandler.bind(this, 'monthly')}
                                 key="monthly"
                                 className={cx({
                                   active: this.state.dayTypeState === 'monthly',
                                   disabled: days < 30
                                 })}
                                 disabled={days < 30}
                                 style={{
                                   cursor: days < 30 ? 'not-allowed' : 'pointer'
                                 }}>
                                 月
                              </button>
                            </div>
                            </div>
                          }
                          >
                          <ChartWidget
                            store={this.state.chart0}
                            tooltipShared={true}
                            key={this.state.chart0Key}
                          />
                        </Card>
                      </div>
                    </div>

                    <div className="pure-g">
                      <div className="pure-u-1">
                        <div style={{marginTop:'15px'}}>
                          <Card title={
                            <span>
                              活跃用户明细
                              <i className="iconfont" data-tip={tips.activeanalysis_activeuser_detail}>&#xe663;</i>
                            </span>
                          } extra={
                            <a href={exportUrl} className="btn-blue">导出</a>
                          }>
                            <ActiveUserGrid
                              store={this.state.grid}
                              formatType={this.state.dayTypeState}
                            />
                          </Card>
                        </div>
                      </div>
                    </div>
                  </Tab.Panel>

                  <Tab.Panel title="活跃时段" key="2">
                    <div className="pure-g">
                      <div className="pure-u-1 pure-u-md-1-2">
                        <div style={{marginRight:'7.5px'}}>
                          <Card
                            title={
                              <span>
                                活跃用户
                                <i className="iconfont" data-tip={tips.activeanalysis_activeuser}>&#xe663;</i>
                              </span>
                            }
                            extra={
                              <DateComparerPicker
                                id="aliveNum"
                                spanTime={duration.valueOf()}
                                displayText={this.state.aliveNumComparer.displayText}
                                style={{'float':'right', marginLeft:'5px'}} />
                            }
                            >
                            <ChartWidget
                              store={this.state.chart1_1}
                              tooltipShared={true}
                              tooltipFormat={this.state.chart1_1_tooltipFormat}
                              key={this.state.chart1_1Key}
                              chartSettings={{
                                tooltip:{
                                  useHTML:true,
                                  shared: true
                                },
                                xAxis:{
                                  min:moment().startOf('day').valueOf(),
                                  max:moment().startOf('day').add(23,'hours').valueOf()
                                }
                              }}
                            />
                          </Card>
                        </div>
                      </div>

                      <div className="pure-u-1 pure-u-md-1-2">
                        <div style={{marginLeft:'7.5px'}}>
                          <Card
                            title={
                              <span>
                                启动次数
                              </span>
                            }
                            extra={
                              <DateComparerPicker
                                id="startNum"
                                spanTime={duration.valueOf()}
                                displayText={this.state.startNumComparer.displayText}
                                style={{'float':'right', 'marginLeft':'5px'}} />
                            }
                            >
                            <ChartWidget
                              store={this.state.chart1_2}
                              tooltipShared={true}
                              tooltipFormat={this.state.chart1_1_tooltipFormat}
                              key={this.state.chart1_2Key}
                              chartSettings={{
                                tooltip:{
                                  useHTML:true,
                                  shared: true
                                },
                                xAxis:{
                                  min:moment().startOf('day').valueOf(),
                                  max:moment().startOf('day').add(23,'hours').valueOf()
                                }
                              }}
                            />
                          </Card>
                        </div>
                      </div>

                    </div>

                    <div className="pure-g">
                      <div className="pure-u-1 pure-u-md-1-2">
                        <div style={{marginRight:'7.5px',marginTop:'15px'}}>
                          <Card title={'高峰时段'}>
                            <ActiveBusyGrid store={this.state.grid1_1} />
                          </Card>
                        </div>
                      </div>

                      <div className="pure-u-1 pure-u-md-1-2">
                        <div style={{marginLeft:'7.5px',marginTop:'15px'}}>
                          <Card title={'低谷时段'}>
                            <ActiveIdleGrid store={this.state.grid1_2} />
                          </Card>
                        </div>
                      </div>

                    </div>
                  </Tab.Panel>

                </Tab>
              </div>
            </div>
          </div>



        </div>
      </div>
    );

  }

}

RootView.defaultProps = {
  Scope: RootScope
};
